<template>
  <el-dialog
    v-model="diaShow"
    :close-on-click-modal="false"
    title="选择渠道优惠券"
    width="60%"
    append-to-body
    :before-close="handleClose"
  >
    <div class="content">
      <div class="content pending">
        <div class="formSearch">
          <el-form :inline="true" :model="formInline">
            <el-form-item label="优惠券名称">
              <el-input
                v-model="formInline.couponName"
                maxlength="20"
                clearable
                placeholder="请输入内容"
                @blur="search"
              />
            </el-form-item>
            <el-form-item label="优惠券类型">
              <el-select
                v-model="formInline.couponType"
                placeholder="请选择优惠券类型"
                @change="search"
              >
                <el-option label="全部" value="null" />
                <el-option label="满减券" value="1" />
                <el-option label="折扣券" value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-select
                v-model="formInline.state"
                placeholder="请选择优惠券状态"
                @change="search"
              >
                <el-option label="全部" value="null" />
                <el-option label="未开始" value="0" />
                <el-option label="进行中" value="1" />
                <el-option label="已结束" value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间">
              <el-date-picker
                v-model="formInline.dates"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD HH:mm:ss"
                @change="search"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" plain @click="search">查询 </el-button>
              <el-button type="primary" plain @click="clear">重置 </el-button>
              <!-- <el-button type="primary" plain @click="addActivity">新增</el-button> -->
            </el-form-item>
          </el-form>
        </div>
        <!-- 表格 -->
        <div class="tableBox">
          <el-table
            ref="multipleTableRef"
            :data="tableData"
            border
            :header-cell-style="{ background: '#EEF3FF', color: '#333333' }"
            tooltip-effect="dark"
            style="width: 100%"
            :row-key="(row) => row.shopCouponId"
            @selection-change="handleTableSelection"
          >
            <el-table-column type="selection" reserve-selection />
            <el-table-column label="优惠券名称" width="220">
              <template #default="scope">{{ scope.row.couponName }}</template>
            </el-table-column>
            <el-table-column label="类型" show-overflow-tooltip>
              <template #default="scope">
                <span v-if="scope.row.couponType === 1">满减券</span>
                <span v-if="scope.row.couponType === 2">折扣券</span>
              </template>
            </el-table-column>
            <el-table-column label="状态" show-overflow-tooltip>
              <template #default="scope">
                <span v-if="scope.row.state === 0">未开始</span>
                <span v-if="scope.row.state === 1">进行中</span>
                <span v-if="scope.row.state === 2">已结束</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="content"
              label="内容"
              show-overflow-tooltip
            />
            <el-table-column
              prop="createTime"
              label="创建时间"
              show-overflow-tooltip
            />
          </el-table>
          <div class="fenye">
            <el-pagination
              :current-page="formInline.page"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="formInline.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, toRefs, watch, nextTick } from 'vue'
import { useVModel } from '@vueuse/core'
import {
  getCoupon,
  delCoupon,
  getCouponData,
  stopCoupon,
} from '@/api/marketing'

function CouponQueryForm () {
  this.type = 2
  this.couponName = '' // 优惠券名称
  this.couponType = null // 优惠券类型
  this.dates = [] // 创建时间数组
  this.endTime = '' // 创建时间结束时间
  this.page = 1 // 当前页
  this.pageSize = 10 // 每页记录数
  this.startTime = '' // 创建时间开始时间
  this.state = '1' // 优惠券状态
  this.takeEnd = '' // 活动结束时间
  this.stockNumber = 1 // 库存限制
}

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: () => false,
  },
  defaultSelection: {
    type: Array,
    default: () => {
      return []
    },
  },
  takeEnd: {
    type: String,
    default: () => '',
  },
  stockNumber: {
    type: Number,
    default: () => 1,
  },
})

const emits = defineEmits(['update:modelValue', 'cancel', 'confirm'])
const diaShow = useVModel(props, 'modelValue', emits)
const multipleTableRef = ref(null)
const { defaultSelection, takeEnd, stockNumber } = toRefs(props)
const formInline = ref(new CouponQueryForm())
const isDataVisible = ref(false) // 数据效果展示
const dataInfo = ref([]) // 商品使用数据
const total = ref(1)
const tableData = ref([])
const dataEffect = ref([])
const selection = ref([])

watch(defaultSelection, (newVal) => {
  nextTick(() => {
    selection.value = newVal
    handleManageSelection()
  })
}, { deep: true })

watch(diaShow, (newVal) => {
  if (newVal) {
    formInline.value.takeEnd = takeEnd.value
    formInline.value.stockNumber = stockNumber.value
    getAll()
  } else {
    tableData.value = []
  }
}, { deep: true })

const handleManageSelection = () => {
  // 清空所有选中
  multipleTableRef.value?.clearSelection()
  tableData.value.forEach((item) => {
    const find = defaultSelection.value.find(
      (i) => i.shopCouponId === item.shopCouponId
    )
    if (find) {
      // 勾选指定行
      nextTick(() => {
        multipleTableRef.value?.toggleRowSelection(item, true)
      })
    }
  })
}
const handleTableSelection = (s) => {
  selection.value = s
}
const handleClose = () => {
  diaShow.value = false
  emits('cancel', selection.value)
  selection.value = []
}
const handleConfirm = () => {
  emits('confirm', selection.value)
  console.log('确定')
  selection.value = []
  diaShow.value = false
}
//  查询
const search = () => {
  total.value = 1
  formInline.value.page = 1
  if (formInline.value.dates && formInline.value.dates.length !== 0) {
    formInline.value.startTime = formInline.value.dates[0]
    formInline.value.endTime = formInline.value.dates[1]
  } else {
    delete formInline.value.startTime
    delete formInline.value.endTime
  }
  getAll()
}
// 清除
const clear = () => {
  formInline.value = new CouponQueryForm()
  formInline.value.takeEnd = takeEnd.value
  formInline.value.stockNumber = stockNumber.value
  getAll()
}
const handleSizeChange = (val) => {
  formInline.value.pageSize = val
  getAll()
}
const handleCurrentChange = (val) => {
  formInline.value.page = val
  getAll()
}
// 停止优惠券活动
const stopFn = (id) => {
  stopCoupon({ shopCouponId: id }).then((res) => {
    if (res.code === '') {
      ElMessage.success('停止成功')
      formInline.value.page = 1
      getAll()
    } else {
      ElMessage.error(res.message)
    }
  })
}
// 初始化查询所有数据
const getAll = async () => {
  const res = await getCoupon(formInline.value)
  total.value = res.data.total
  tableData.value = res.data.list
  handleManageSelection()
}
// 显示数据效果
const showData = (id) => {
  getCouponData({ shopCouponId: id }).then((res) => {
    if (res.code === '') {
      dataInfo.value = res.data
    } else {
      ElMessage.error(res.message)
    }
  })
  isDataVisible.value = true
}
// 删除优惠券
const delCouponFn = (data) => {
  delCoupon({ shopCouponId: data.shopCouponId }).then((res) => {
    if (res.code === '') {
      ElMessage.success('删除成功')
      formInline.value.page = 1
      getAll()
    } else {
      ElMessage.error(res.message)
    }
  })
}
</script>

<style lang="scss" scoped>
.pending {
  padding: 30px;
}

.fenye {
  margin-top: 20px;
}

.dataEffect {
  .couponTit {
    margin: 20px 0;
  }

  .dataListBox {
    display: flex;
    justify-content: center;
    margin: 30px 0;

    .dataItem {
      width: 220px;
      height: 120px;
      border-radius: 8px;
      border: 1px solid #999999;
      text-align: center;
      margin: 0 10px;

      span {
        display: block;
        margin-top: 35px;
      }
    }
  }

  .tabListInfo {
    margin: 20px 0;
  }
}
</style>

<style scoped>
:deep(.btnList) .delCls {
  margin-left: 10px;
}

:deep(.group-dialog) .el-dialog__headerbtn .el-dialog__close {
  color: #ffffff;
}
</style>
